package com.scanner.net;


import java.io.File;
import java.util.concurrent.TimeUnit;


import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 纪书彬
 * 2019年4月2日10:27:55
 * 下载工具类
 */
public class RxDownLoadUtils {

    private static final int DEFAULT_TIMEOUT = 15;
    private String downUrl;
    private RxProgressListener progressListnenr;
    private Retrofit retrofit;
    private final RxFileDownLoadObserver<File> fileDownLoadObserver;


    public RxDownLoadUtils(String downUrl, RxProgressListener progressListener){
        this.downUrl = downUrl;
        this.progressListnenr = progressListener;
        RxDownLoadInterceptor mInterceptor = new RxDownLoadInterceptor(progressListener);


        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(mInterceptor)
                .retryOnConnectionFailure(true)
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory())
                .hostnameVerifier(new TrustAllCerts.TrustAllHostnameVerifier())
                .readTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .build();

        retrofit = new Retrofit.Builder()
                .baseUrl(InterBase.HTTPURL)
                .client(httpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        fileDownLoadObserver = new RxFileDownLoadObserver<>(progressListener);
    }



    public void download(final String filePath, final String fileName){
        progressListnenr.onStartDownload();
        retrofit.create(EDAppService.class)
                .download(downUrl)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .map(new Function<ResponseBody, File>() {
                    @Override
                    public File apply(ResponseBody responseBody) throws Exception {
                        return fileDownLoadObserver.saveFile(responseBody, filePath, fileName);
                    }
                })
                .observeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(fileDownLoadObserver);

    }

}
